<?php

class CustomersController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/customer';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
             
               'users'=>array('@'),
            ),
         
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionAjaxView($id){
      
        $rs=$this->loadModel($id)->getAttributes();
        echo json_encode($rs);
        Yii::app()->end();
      
    }
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
 
   
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate() {
         $id = Yii::app()->user->custno;
        $model = $this->loadModel($id);
        
     
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        
        if (isset($_POST['Customers'])) {
      
                $model->attributes = $_POST['Customers'];                               
                $model->save();


         
            
        }
        
        $this->render('update', array(
            'model' => $model,
        ));
    }
   
 
  

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Customers::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'customers-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    
    /*
     * Param: query, page, sort, dir
     * Get customer list
     * return json array totalCount and array of customer
     */
    public function actionGetCustomerList($page=1,$sort=NULL,$dir=NULL){
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if($page>0)$page--;
        
        $customers= new CActiveDataProvider('Customers',array(
            
            'criteria'=>array(
                'order'=>$sort!=NULL?$sort.' '.$dir:'',
            ),
            'pagination'=>array(
                'pageSize'=>20,
                'currentPage'=>$page,
            ),
        ));
        
        $rs=array();
        if($customers->getTotalItemCount()>0){
            $rs['totalCount']=$customers->getTotalItemCount();
            $rs['type']='Customers';
            foreach($customers->getData() as $item){
                $rs['data'][]=$item->getAttributes();
                
            }
            echo json_encode($rs);
        }
        Yii::app()->end();
        
    }
    public function actionGetCustomer($query){
        $customer=Customers::model()->find('id=:id',array('id'=>$query));
        $rs=$customer->getAttributes();
        echo json_encode($rs);
        Yii::app()->end();
    }
    
    public function actionPopupCreateCustomer(){
        $this->layout='popup';
        $model = new Customers;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        
        if (isset($_POST['Customers'])) {
            $model->attributes = $_POST['Customers'];
            if ($model->save()){
                
                $this->redirect(array('view', 'id' => $model->custno));
            }
                
        }
        $this->render('popupCreateCustomer',array(
            'model'=>$model,
        ));
    }
public function actionDashboard(){
       $this->render('dashboard');
    }
    public function actionEntitySearch($entityId, $entityName) {
        $url = "";
        $success = true;
        $errorMsg = "";
        $custno =  Yii::app()->user->custno;
        switch($entityName) {
            case "invoices":
                $model = Invoice::model()->findByPk($entityId);
                if ($model == NULL || $model->custno !=$custno) {
                    $success = false;
                    $errorMsg = "The Invoice/Sales Order/Quotation:\"$entityId\" was not found, please try again";
                } else {
                    $url = Yii::app()->createAbsoluteUrl('pdf', array('invno' => $entityId));
                }
                break;
            case "contract":
                $model = Contracts::model()->findByPk($entityId);
                if ($model == NULL|| $model->custno !=$custno) {
                    $success = false;
                    $errorMsg = "The Contract:\"$entityId\" was not found, please try again";
                } else {
                    $url = Yii::app()->createAbsoluteUrl('customerportal/contracts/update', array('contractid' => $entityId));
                }
                break;
 	    case "dispatch":
                $model = Dispatchdetails::model()->findByPk($entityId);
                if ($model == NULL|| $model->custno !=$custno) {
                    $success = false;
                    $errorMsg = "The Dispatch:\"$entityId\" was not found, please try again";
                } else {
                    $url = Yii::app()->createAbsoluteUrl('customerportal/dispatchdetails/update', array('dispatch' => $entityId));
                }
                break;
            case "job":
                $model = Jobs::model()->findByPk($entityId);
                if ($model == NULL || $model->custno !=$custno) {
                    $success = false;
                    $errorMsg = "The Job:\"$entityId\" was not found, please try again";
                } else {
                    $url = Yii::app()->createAbsoluteUrl('customerportal/jobs/update', array('jobid' => $entityId));
                }
                break;
            default:
                $success = false;
                $errorMsg = "Please select proper search entity.";
        }
        $ret = array(
            "url" => $url,
            "success" => $success,
            "errorMsg" => $errorMsg
        );
        echo json_encode($ret);
    }
}
